package com.suyunyou.spider.data;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.suyunyou.spider.plugins.IPagePlugin;
import com.suyunyou.spider.utils.PluginUtil;

/**
 * 提取页面的链接
 * @author yuejing
 * @date 2016年6月25日 下午1:06:06
 * @version V1.0.0
 */
public class FetcherPageLinkData {
	
	private static final Logger LOGGER = Logger.getLogger(FetcherPageLinkData.class);
	
	private static List<String> fetcherPageLinks = new ArrayList<String>();
	
		/**
		 * 获取待提取的第一个链接
		 * @return
		 */
		public static String get() {
			return fetcherPageLinks.size() > 0 ? fetcherPageLinks.get(0) : null; 
		}
		
		/**
		 * 记录网站首页
		 * @param link
		 * @return
		 */
		/*public static void addSite(String link) {
			if(!fetcherPageLinks.contains(link)) {
				fetcherPageLinks.add(link);
			}
		}*/
		
		/**
		 * 记录
		 * @param link
		 * @return
		 */
		public static void add(String link) {
			if(!fetcherPageLinks.contains(link)) {
				List<IPagePlugin> plugins = PluginUtil.getPagePlugins();
				for (IPagePlugin plugin : plugins) {
					try {
						if(plugin.isHandle(link)) {
							fetcherPageLinks.add(link);
							break;
						}
					} catch (Exception e) {
						LOGGER.error(e.getMessage(), e);
					}
				}
			}
		}
		
		/**
		 * 移除
		 * @param link
		 */
		public static void remove(String link) {
			fetcherPageLinks.remove(link);
		}

		public static void clear() {
			fetcherPageLinks.clear();
		}
		
	/*//key的前缀
	private final static String PREFIX = "fetcherPageLinks";
	
	private static BaseCache cache;
	private static BaseCache getCache() {
		if(cache == null) {
			cache = new BaseCache();
		}
		return cache;
	}
	
	private static String keyFetcherPageLinks() {
		return getCache().getKey(PREFIX);
	}

	*//**
	 * 获取待提取的第一个链接
	 * @return
	 *//*
	public static String get() {
		List<String> list = getCache().get(keyFetcherPageLinks());
		return list != null && list.size() > 0 ? list.get(0) : null;
	}
	
	*//**
	 * 记录
	 * @param link
	 * @return
	 *//*
	public static synchronized void add(String link) {
		String key = keyFetcherPageLinks();
		List<String> list = getCache().get(key);
		if(list == null) {
			list = new ArrayList<String>();
		}
		if(!list.contains(link)) {
			List<IPlugin> plugins = PluginUtil.getPlugins();
			for (IPlugin plugin : plugins) {
				try {
					plugin.setLink(LinkData.getLink(link));
					if(plugin.isHandle()) {
						list.add(link);
						getCache().set(key, list);
						break;
					}
				} catch (Exception e) {
					LOGGER.error(e.getMessage(), e);
				}
			}
		}
	}
	
	*//**
	 * 移除
	 * @param link
	 *//*
	public static synchronized void remove(String link) {
		String key = keyFetcherPageLinks();
		List<String> list = getCache().get(key);
		if(list != null) {
			list.remove(link);
			getCache().set(key, list);
		}
	}

	public static void reset() {
		String key = keyFetcherPageLinks();
		getCache().set(key, null);
	}*/
}